package com.hcmus.facebook;



import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.facebook.FacebookRequestError;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.model.GraphObject;
import com.hcmus.arLocation.NetworkDataSource;
import com.hcmus.armobile.ServerUtilities;

import common.Promotion;
import common.PromotionImage;

import android.R;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.Toast;

import java.util.concurrent.ArrayBlockingQueue;

public class MainActivity extends Activity {

	private static final String APP_ID = "495888260472741";
	private static final String[] PERMISSIONS = new String[] {"publish_stream"};
	private static String messagePost = "";
	private static final String TOKEN = "4297919167e72872178b1cc820ffb9a9";
        private static final String EXPIRES = "expires_in";
        private static final String KEY = "facebook-credentials";

	private Facebook facebook;
	private String messageToPost;
	
	private boolean finishActivity = true;
	
	AsyncTask<Void, Void, Void> mRegisterTask;
	

	public boolean saveCredentials(Facebook facebook) {
        	Editor editor = getApplicationContext().getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
        	editor.putString(TOKEN, facebook.getAccessToken());
        	editor.putLong(EXPIRES, facebook.getAccessExpires());
        	return editor.commit();
    	}
	
	public boolean deleteCredentials(Facebook facebook) {
    	Editor editor = getApplicationContext().getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
    	editor.putString(TOKEN, null);    	
    	return editor.commit();
	}
	

    	public boolean restoreCredentials(Facebook facebook) {
        	SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(KEY, Context.MODE_PRIVATE);
        	facebook.setAccessToken(sharedPreferences.getString(TOKEN, null));
        	facebook.setAccessExpires(sharedPreferences.getLong(EXPIRES, 0));
        	return facebook.isSessionValid();
    	}
    	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//setContentView(R.layout.activity_share_on_facebook);
		/*
		if (android.os.Build.VERSION.SDK_INT > 9) {
		    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		    StrictMode.setThreadPolicy(policy);
		}
		*/
		try{
			
			Intent i = getIntent();
			messageToPost = i.getStringExtra("message");
			if (messageToPost == null){
				messageToPost = "post:  " + new Date().toString();
			}
			//Bundle extra = i.getExtras();
			//promotionPost = extra.getParcelableArrayList("promotionPost");
			ArrayList<PromotionImage> lst = new ArrayList<PromotionImage>();
			lst.add(new PromotionImage(1, "http://myrrix.com/wp-content/uploads/2012/06/stackoverflow.png", 1));
			Promotion p = new Promotion(1,"promotion test face" , 1, "152000", "52000", "30", 20130425, 20130530, 1500," description promotion test", lst , "");
			promotionPost = p;
			
			facebook = new Facebook(APP_ID);	
			restoreCredentials(facebook);
			requestWindowFeature(Window.FEATURE_NO_TITLE);		
			//setContentView(R.layout.facebook_dialog);
			
			//AlertDialogManager alert = new AlertDialogManager();
			
			DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
			    @Override
			    public void onClick(DialogInterface dialog, int which) {
			        switch (which){
			        case DialogInterface.BUTTON_POSITIVE:
			            //Yes button clicked			        	
			        	if (! facebook.isSessionValid()) {
			        			// Register on our server
									// On server creates a new user
								
			        		
			        	loginAndPostToWall();	
			        			
			        		
			    		}
			    		else {
			    			
			    		//postToWall(messageToPost);
			    			
			    			/*MainActivity.runOnUiThread(new Runnable() {
			    				   public void run() {
			    				      //put your code here
			    					   postToWall(messageToPost);
			    				   }
			    				});
			    			*/
			    			mRegisterTask = new AsyncTask<Void, Void, Void>() {

								@Override
								protected Void doInBackground(Void... params) {
									// Register on our server
									// On server creates a new user
									postToWall(messageToPost);
									return null;
								}

								@Override
								protected void onPostExecute(Void result) {
									mRegisterTask = null;
								}

							};
							mRegisterTask.execute(null, null, null);
							
			    			
			    			/*try {
			        			exeService.execute(new Runnable() {

			        				public void run() {
			        					for (NetworkDataSource source : sources.values())
			        						postToWall(messageToPost);
			        				}
			        			});
			        		} catch (RejectedExecutionException rej) {
			        			Log.e("error on face", "Not running new download Runnable, queue is full.");
			        		} catch (Exception e) {
			        			Log.e("error on face", "Exception running download Runnable.", e);
			        		}
			    			*/
							finish();
			    		}			        	
			            break;

			        case DialogInterface.BUTTON_NEGATIVE:
			            //No button clicked
			        	
			        	try {
			        		facebook = new Facebook(APP_ID);			        		
							facebook.logout(getApplicationContext());
							saveCredentials(facebook);
						} catch (MalformedURLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}			        	
			        	finish();			        	
			            break;
			        }
			    }
			};
			
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Do you want to post message to your wall?").setPositiveButton("Yes", dialogClickListener)
			    .setNegativeButton("No", dialogClickListener).show();
			
			
			
			
			//messageToPost = facebookMessage;
		
		}catch(Exception e){
			Log.e("Error: ", e.toString());
		}
		
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	

	public void doNotShare(View button){
		finish();
	}
	public void share(View button){
		if (! facebook.isSessionValid()) {
			loginAndPostToWall();
		}
		else {
			mRegisterTask = new AsyncTask<Void, Void, Void>() {

				@Override
				protected Void doInBackground(Void... params) {
					// Register on our server
					// On server creates a new user
					postToWall(messageToPost);
					finish();
					return null;
				}

				@Override
				protected void onPostExecute(Void result) {
					mRegisterTask = null;
				}

			};
			mRegisterTask.execute(null, null, null);
			
		//	postToWall(messageToPost);
			finish();
		}
	}

	public void loginAndPostToWall(){
		 facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener());
	}
	
	  private interface GraphObjectWithId extends GraphObject {
	        String getId();
	    }
	  
	private void showPublishResult(String message, GraphObject result, FacebookRequestError error) {
        String title = null;
        String alertMessage = null;
        if (error == null) {
            title = "title";
            String id = result.cast(GraphObjectWithId.class).getId();
            alertMessage = "Post thanh cong" + message+ id;
            
        } else {
            title = "Error";
            alertMessage = error.getErrorMessage();
        }

        new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(alertMessage)
                .setPositiveButton(title , null)
                .show();
    }
	
	
	public void postToWall(final String message){
		
		
		/*Runnable runnable = new Post2FaceBackground(promotionPost,message);
	    Thread background  = new Thread(runnable);
	    background.start();*/
	    
	//	byte[] data = null;
		//Bitmap image = BitmapFactory.decodeResource(this.getResources(), R.drawable.alert_light_frame);
		//ByteArrayOutputStream baos = new ByteArrayOutputStream();
        //image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
       // data = baos.toByteArray();
		/*Bundle parameters = new Bundle();
                parameters.putString("message", message);
                parameters.putString("description", "topic share");
               // parameters.putByteArray("picture", data);  
*/
		

		Bundle params = new Bundle();
	
        params.putString("caption",message);
        params.putString("description",promotionPost.getDescription());
        params.putString("link", 
                "http://vinaecom.com/location_advertisement_mobile/index.php?route=armobile/promotiondetail&promotion_id=67");
        params.putString("picture","http://myrrix.com/wp-content/uploads/2012/06/stackoverflow.png");                          
        params.putString("name",promotionPost.getName());       
	
       // parameters.putByteArray("picture", data);  

        
                try {
        	        facebook.request("me");
			String response = facebook.request("me/feed", params, "POST");
			
			Log.d("Tests", "got response: " + response);
			if (response == null || response.equals("") ||
			        response.equals("false")) {
				//showToast("Blank response.");
			}
			else {
				//showToast("Message posted to your facebook wall!");
				//mRegisterTask.cancel(true);
			}
			//finish();
		} catch (Exception e) {
			//showToast("Failed to post to wall!");
			e.printStackTrace();
			//mRegisterTask.cancel(true);
			finish();
		}
                finish();
                
               
	}

	class LoginDialogListener implements DialogListener {
	    public void onComplete(Bundle values) {
	    	saveCredentials(facebook);
	    	if (messageToPost != null){	    			
				postToWall(messageToPost);
				finish();	    		
	    	}
	    }
	    public void onFacebookError(FacebookError error) {
	    	showToast("Authentication with Facebook failed 11 !");
	        finish();
	    }
	    public void onError1(DialogError error) {
	    	showToast("Authentication with Facebook failed 22 !");
	        finish();
	    }
	    public void onCancel() {
	    	showToast("Authentication with Facebook cancelled 33 !");
	        finish();
	    }
		@Override
		public void onError(DialogError e) {
			// TODO Auto-generated method stub
			
		}
	}

	private void showToast(String message){
		Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
	}
	
	
	public class Post2FaceBackground implements Runnable{
		public Promotion p = null;
		public String message = "";
		
		public Post2FaceBackground(){			
		}
		
		public Post2FaceBackground(Promotion p , String message){
			this.p = p;
			this.message = message;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
						 
			postToWall();
		}
		
		public void postToWall(){
			
			//	byte[] data = null;
				//Bitmap image = BitmapFactory.decodeResource(this.getResources(), R.drawable.alert_light_frame);
				//ByteArrayOutputStream baos = new ByteArrayOutputStream();
		        //image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		       // data = baos.toByteArray();
				/*Bundle parameters = new Bundle();
		                parameters.putString("message", message);
		                parameters.putString("description", "topic share");
		               // parameters.putByteArray("picture", data);  
		*/
				Bundle params = new Bundle();
			
		        params.putString("caption",message);
		        params.putString("description",p.getDescription());
		        params.putString("link", 
		                "http://vinaecom.com/location_advertisement_mobile/index.php?route=armobile/promotiondetail&promotion_id=67");
		        params.putString("picture","http://myrrix.com/wp-content/uploads/2012/06/stackoverflow.png");                          
		        params.putString("name",p.getName());       
			
		       // parameters.putByteArray("picture", data);  

		        
		                try {
		        	        facebook.request("me");
					String response = facebook.request("me/feed", params, "POST");
					
					Log.d("Tests", "got response: " + response);
					if (response == null || response.equals("") ||
					        response.equals("false")) {
						showToast("Blank response.");
					}
					else {
						showToast("Message posted to your facebook wall!");
						//mRegisterTask.cancel(true);
					}
					//finish();
				} catch (Exception e) {
					showToast("Failed to post to wall!");
					e.printStackTrace();
					//mRegisterTask.cancel(true);
					finish();
				}
		      
		     finish();
			}

		
		
	}
	

}
